package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.*;
import com.itheima.config.BaseContext;
import com.itheima.dao.OrderDao;
import com.itheima.dto.ParamPageDto;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    public int add(Orders orders, HttpSession session) {
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        User user = (User) session.getAttribute("user");
        orders.setStatus(2);
        orders.setUserId(user.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName()!=null?addressBook.getProvinceName():"")
                +(addressBook.getCityName()!=null?addressBook.getCityName():"")
                +(addressBook.getDistrictName()!=null?addressBook.getDistrictName():"")
                +addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        int i = orderDao.insert(orders);
        if (i>0){
            List<OrderDetail> list = shoppingCartService.findByUid(user.getId()).stream().map(aa -> {
                OrderDetail detail = new OrderDetail();
                BeanUtils.copyProperties(aa, detail);
                detail.setId(null);
                detail.setOrderId(orders.getId());
                return detail;
            }).collect(Collectors.toList());
            int a=0;
            for (OrderDetail orderDetail : list) {
                a+=orderDetailService.add(orderDetail);
            }
            if(a==list.size()){
                shoppingCartService.clean();
                return 1;
            }
        }
        return 0;
    }

    @Override
    public IPage<Orders> findPage(ParamPageDto paramPage,HttpSession session) {
        IPage<Orders> page = new Page<>(paramPage.getPage(), paramPage.getPageSize());
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(paramPage.getNumber()!=null,Orders::getNumber,paramPage.getNumber());
        lqw.ge(paramPage.getBeginTime()!=null,Orders::getCheckoutTime,paramPage.getBeginTime());
        lqw.le(paramPage.getEndTime()!=null,Orders::getCheckoutTime,paramPage.getEndTime());
        if (session!=null){
            User user = (User) session.getAttribute("user");
            if (user!=null){
                lqw.eq(Orders::getUserId,user.getId());
            }
        }
        orderDao.selectPage(page,lqw);
        List<Orders> records = page.getRecords();
        Collections.sort(records, new Comparator<Orders>() {
            @Override
            public int compare(Orders o1, Orders o2) {
                return o2.getOrderTime().compareTo(o1.getOrderTime());
            }
        });
        page.setRecords(records);
        return page;
    }

    @Override
    public int Update(Orders orders) {
        Orders orders1 = orderDao.selectById(orders.getId());
        orders1.setStatus(orders.getStatus());
        return orderDao.updateById(orders1);
    }

    @Override
    public ShoppingCart again(Orders orders) {
        Orders orders1 = orderDao.selectById(orders.getId());
        List<OrderDetail> orderDetailList = orderDetailService.findByOid(orders.getId());
        ShoppingCart cart=null;
        for (OrderDetail detail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setUserId(BaseContext.getThreadLocal());
            shoppingCart.setCreateTime(LocalDateTime.now());
            cart = shoppingCartService.add(shoppingCart);
        }
        return cart;
    }
}
